import axios from "axios";
import mpAdapter from "axios-miniprogram-adapter";
import { globalParams } from "../../public/config";

axios.defaults.adapter = mpAdapter;

const instance = axios.create({
  baseURL: globalParams.baseUrl,
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    const res = error.data;
    if (res.code != 200) {
      uni.showToast({
        title: res.msg || "出现错误",
        icon: "error",
        duration: 1000,
        mask: false,
      });
    }
    return error;
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    const res = response.data;
    if (res.code != 200) {
      uni.showToast({
        title: res.msg || "出现错误",
        icon: "error",
        duration: 1000,
        mask: false,
      });
    }
    return response;
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    uni.showToast({
      title: "系统错误",
      icon: "error",
      duration: 1000,
      mask: false,
    });
    return error;
  }
);

const request = {
  post(url, params) {
    return instance.post(url, params, {
      transformRequest: [
        (params) => {
          return JSON.stringify(params);
        },
      ],
      headers: {
        "Content-Type": "application/json",
      },
    });
  },
  put(url, params) {
    return instance.put(url, params, {
      transformRequest: [
        (params) => {
          return JSON.stringify(params);
        },
      ],
      headers: {
        "Content-Type": "application/json",
      },
    });
  },
  get(url, params) {
    let _params;
    let urlTmp = url;

    if (params === undefined) {
      _params = "";
    } else {
      _params = "?";
      for (const key in params) {
        // eslint-disable-next-line no-prototype-builtins
        if (params.hasOwnProperty(key) && params[key] !== null) {
          _params += `${key}=${params[key]}&`;
        }

        urlTmp = urlTmp.replace(
          new RegExp("\\{" + key + "\\}", "g"),
          params[key]
        );
      }
      _params = _params.substring(0, _params.length - 1);
    }

    return instance.get(`${urlTmp}${_params}`);
  },
  delete(url, params) {
    let _params;
    let urlTmp = url;

    if (params === undefined) {
      _params = "";
    } else {
      _params = "?";
      for (const key in params) {
        // eslint-disable-next-line no-prototype-builtins
        if (params.hasOwnProperty(key) && params[key] !== null) {
          _params += `${key}=${params[key]}&`;
        }

        urlTmp = urlTmp.replace(
          new RegExp("\\{" + key + "\\}", "g"),
          params[key]
        );
      }
      _params = _params.substring(0, _params.length - 1);
    }

    return instance.delete(`${urlTmp}${_params}`);
  },
};

export { request };
